package com.syf.core.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 有限时间内，阻塞式启动SyServer
 */
@Slf4j
public class SyServerBoostrap implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (SyServer.class.isAssignableFrom(bean.getClass())) {
            CountDownLatch latch = new CountDownLatch(1);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ((SyServer) bean).startup(latch);
                }
            }).start();

            try {
                if (latch.await(30, TimeUnit.SECONDS)) ;
            } catch (InterruptedException e) {
                log.error("SyServer: " + beanName + " 启动失败！", e);
                throw new RuntimeException(e);
            }
        }

        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
